<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/7/6 0006
 * Time: 11:17
 */

namespace app\api\controller\v1\agent;


use app\api\controller\v1\Agent;
use think\Db;

class MobileModify extends Agent
{
    public function save()
    {
        $data = $this->_input([
            'id' => $this->request->post('id'),
            'new_mobile' => $this->request->post('new_mobile'),
            'smscode' => $this->request->post('smscode'),
        ],[
            'id' => 'require',
            'new_mobile' => 'require|mobile',
            'smscode' => 'require'
        ]);
        //验证手机验证码
        $cache = cache($cachekey = "send_register_sms_{$data['new_mobile']}");
        if(!isset($cache['captcha']) || $cache['captcha'] != $data['smscode']){
            $this->error('短信验证码错误！');
        }
        $modify = Db::name('AgentModifyMobile')->where([
            ['id','eq',$data['id']],
            ['aid','eq',$this->aid],
            ['status','eq','0']
        ])->find();
        empty($modify) && $this->error('网络错误，请稍后再试！');
        Db::transaction(function() use($data){
            Db::name('Agent')->where('id',$this->aid)->setField('phone',$data['new_mobile']);
            Db::name('AgentModifyMobile')->where('id',$data['id'])->update([
                'new_mobile' => $data['new_mobile'],
                'status' => '1'
            ]);
        });
        $this->success('更换手机号成功！');
    }

    /**
     * 修改手机号接受验证码
     * @param $id
     */
    public function read($id)
    {
        //验证手机验证码
        $cache = cache($cachekey = "send_register_sms_{$this->cleaner->phone}");
        if(!isset($cache['captcha']) || $cache['captcha'] != $id){
            $this->error('短信验证码错误！');
        }
        //插入数据库
        $res = Db::name('AgentModifyMobile')->insertGetId([
            'aid' => $this->aid
        ]);
        if($res)
        {
            $this->success('success',['id' => $res]);
        } else {
            $this->error('网络错误，请稍后再试！');
        }
    }
}